package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: Groovy*
 * @package: com.elite.groovy.callback*
 * @className: apiOBCustomerInfo
 * @description: 外部营销界面获取任务对应客户的自定义字段信息。
 * @author: Tao
 * @date: 2024-10-20 15:00
 * @version: 1.0
 */
public class apiOBCustomerInfo implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiOBCustomerInfo.class);


    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();
        JSONObject outData = JSONObject.fromObject("{\"code\":1,\"message\":\"操作成功\"}");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            outData.put("code", -1);
            outData.put("message", "API被非法IP调用-Request Not Allow!");
            log.warn(outData);
            return outData;
        }

        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "POST" && getMethod != "GET") {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(outData);
            return outData;
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 获取调用数据
        String Syncpram = "";
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        try {
            // 解析请求报文
            JSONObject callJson = JSONObject.fromObject(Syncpram);
            String in_Objective_Guid = GetSFJV(callJson, "objective_guid");

            if (KHUtil.isNull(in_Objective_Guid)) {

                outData.put("code", -1);
                outData.put("message", "HTTP请求调用参数异常,参数值不能为空");

            } else {

                String sql_GetFiled = "select r0.objective_guid, r0.customer_guid, if(r2.field_name is null or r2.field_name = '', r3.column_comment, r2.field_name) as column_name, '' as column_value, r3.column_name as column_field, r3.data_table_name, r3.data_column_name from objective r0 left join pa_activity r1 on r0.pa_tasktype = r1.tab_activity_id left join pa_currency_field_config r2 on r1.tab_activity_id = r2.batch_guid left join pa_ob_custinfo_fields r3 on r2.field_id = r3.column_name where r3.del_flag = 0 and r3.is_show = 1 and r0.objective_guid = ? order by r3.ordinal_position";

                List<Map<String, Object>> GetFiled_List = jt.queryForList(sql_GetFiled, in_Objective_Guid);
                log.debug("检查数据(" + in_Objective_Guid + ") 任务配置字段：" + GetFiled_List);

                if (GetFiled_List.size() > 0) {
                    // 拼接表名&查询客户信息SQL
                    String re_Customer_Guid = "";
                    StringBuilder get_CustInfo_SQL = new StringBuilder();
                    for (int i = 0; i < GetFiled_List.size(); i++) {

                        if (i == 0) {
                            re_Customer_Guid = String.valueOf(GetFiled_List.get(0).get("customer_guid"));
                        }

                        String Data_Column_Name = String.valueOf(GetFiled_List.get(i).get("data_column_name"));

                        if (KHUtil.isNull(String.valueOf(get_CustInfo_SQL))) {
                            get_CustInfo_SQL.append(Data_Column_Name.toLowerCase());
                        } else {
                            get_CustInfo_SQL.append("," + Data_Column_Name.toLowerCase());
                        }

                    }
                    get_CustInfo_SQL.insert(0, "select ");
                    get_CustInfo_SQL.append(" from customer where customer_guid = ? limit 1");
                    List<Map<String, Object>> GetCustInfo_List = jt.queryForList(String.valueOf(get_CustInfo_SQL), re_Customer_Guid);
                    log.debug("检查Customer数据(" + re_Customer_Guid + ") 客户信息结果：" + GetCustInfo_List.toString());

                    // 将查询结果写回字段List
                    if (GetCustInfo_List.size() > 0) {
                        Map<String, Object> GetCustInfo_Map = GetCustInfo_List.get(0);
                        for (int i = 0; i < GetFiled_List.size(); i++) {

                            String Data_Column_Name = String.valueOf(GetFiled_List.get(i).get("data_column_name")).toLowerCase();
                            log.debug("--Data_Column_Name: " + Data_Column_Name);

                            for (String key : GetCustInfo_Map.keySet()) {
                                log.debug("Key: " + key + ", Value: " + GetCustInfo_Map.get(key));
                                if (key.equals(Data_Column_Name)) {
                                    GetFiled_List.get(i).put("Column_Value", GetCustInfo_Map.get(key));
                                    break;
                                }
                            }

                        }
                        log.debug("将查询结果写回字段List(" + re_Customer_Guid + ") List结果：" + GetFiled_List.toString());

                        outData.put("def_data", GetFiled_List);

                    } else {

                        outData.put("code", -1);
                        outData.put("message", "未查询到客户资料信息数据");

                    }
                } else {

                    outData.put("code", -1);
                    outData.put("message", "未找到当前任务的拓展字段信息配置");

                }
            }

        } catch (Exception e) {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用错误，接口处理异常：" + e.getMessage());
            log.error(outData, e);

        }

        log.debug("查询客户信息自定义字段处理完成 耗时(" + (System.currentTimeMillis() - startTime) + ") List结果：" + outData);
        return outData;
    }


    // 解析Json值(此方法增加需要解析的key不存在保护)
    public static String GetSFJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getLong(getKey));
            } catch (Exception e11) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e1) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                    } catch (Exception e2) {
                        try {
                            Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                        } catch (Exception e3) {
                            Rev_Value = "";
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }
}